package com.ifish.leetcode.problem.algorithm;

import com.ifish.leetcode.problem.BaseLeetCodeProblem;

/**
 * Created by iFish on 2017/7/9.
 */

public class _0009 extends BaseLeetCodeProblem {
    @Override
    public String title() {
        return "Palindrome Number";
    }

    @Override
    public void run() {
        super.run();

        printResult(isPalindrome2(123454321));
    }

    public boolean isPalindrome(int x) {
        if (x < 0) return false;

        String s = String.valueOf(x);
        int len = s.length();
        boolean odd = len % 2 == 1;
        int mid = odd ? len / 2 : len / 2 - 1;
        int b = mid, e = odd ? mid : mid + 1;
        if (s.charAt(b) != s.charAt(e))
            return false;

        while (b >= 0 && e < len - 1 && s.charAt(b - 1) == s.charAt(e + 1)) {
            b--;
            e++;
        }
        return b == 0 && e == len - 1;
    }

    public boolean isPalindrome2(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) return false;

        int v = 0;
        while (x > v) {
            v = v * 10 + x % 10; // 翻转至一半
            x = x / 10;
        }
        return x == v || x == v / 10;
    }
}
